package cn.tedu.util;

import cn.tedu.constant.JwtConstants;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 封装生成token和验证token方法
 */
@Component
public class JWTUtil {
    /**
     * 盐值
     * 生成token header.payload.signature
     */
    private static String SIGNATURE="token!Q2W#E$RW";


    @Autowired
    private HttpServletRequest request;

    //public static  Map<String,Object> getUserInfo(HttpServletRequest request){
    //    String header = request.getHeader(JwtConstants.AUTHORIZATION);
    //    String token = header.substring(JwtConstants.AUTHORIZATION_BEARER.length());
    //    DecodedJWT tokenInfo = JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    //    Map<String, Claim> claims = tokenInfo.getClaims();
    //    Set<Map.Entry<String, Claim>> entries = claims.entrySet();
    //    Map<String,Object> map = new HashMap<>();
    //    for (Map.Entry<String, Claim> entry : entries) {
    //        map.put(entry.getKey(),entry.getValue().as(Object.class));
    //    }
    //    //SpsAdminEntity spsAdminEntity = JSON.parseObject(JSON.toJSONString(map), SpsAdminEntity.class);
    //    return map;
    //}

    public  Map<String,Object> getUserInfo(){
        String header = request.getHeader(JwtConstants.AUTHORIZATION);
        String token = header.substring(JwtConstants.AUTHORIZATION_BEARER.length());
        DecodedJWT tokenInfo = JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
        Map<String, Claim> claims = tokenInfo.getClaims();
        Set<Map.Entry<String, Claim>> entries = claims.entrySet();
        Map<String,Object> map = new HashMap<>();
        for (Map.Entry<String, Claim> entry : entries) {
            map.put(entry.getKey(),entry.getValue().as(Object.class));
        }
        //SpsAdminEntity spsAdminEntity = JSON.parseObject(JSON.toJSONString(map), SpsAdminEntity.class);
        return map;
    }

    /**
     * 生成token
     * @param map
     * @return
     */
    public static String getToken(Map<String,Object> map){
        Calendar instance = Calendar.getInstance();
        //30分钟过期
        instance.add(Calendar.SECOND, 60);
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        //payload,用遍历避免多个键值对
        map.forEach((k,v)->{
             builder.withClaim(k,v+"");
        });
        //指定令牌过期时间,设置签名返回token
        String token = builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SIGNATURE));
        return token;
    }

    /**
     * 验证token合法性
     * @param token
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }

    public static void main(String[] args) {
        // 生成令牌
        Map<String,Object> map = new HashMap<>();
        map.put("username", "jx");
        String token = getToken(map);
        System.out.println(token);

        // 测试令牌
        //String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3NDQ3MTYxNzEsInVzZXJuYW1lIjoiangifQ.AmlCy9w4mIFG7JhBraEUts_apMMOwX2z_Q6RdX8ujB0";
        //verify(token);
        //System.out.println("ok");








        // 17000 + 60*1000  一分钟以后的毫秒值
        //

        //Date date = new Date(); // 19.47 + 19.49（毫秒值）
        //
        //long 过期时间 = date.getTime();
        //过期时间 += 2*60*1000;  // 17.02 的毫秒值保存
        //// 17.04分了
        //long l = System.currentTimeMillis();
        //if(l>过期时间){
        //    throw  new RuntimeException("已过期");
        //}


    }






















    public static DecodedJWT getTokenInfo(String token ){
        return   JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);

    }

    public static Map<String,Object> getUserInfo(String token){
        DecodedJWT tokenInfo = JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
        Map<String, Claim> claims = tokenInfo.getClaims();
        Set<Map.Entry<String, Claim>> entries = claims.entrySet();
        Map<String,Object> map = new HashMap<>();
        for (Map.Entry<String, Claim> entry : entries) {
            map.put(entry.getKey(),entry.getValue().as(Object.class));
        }
        //SpsAdminEntity spsAdminEntity = JSON.parseObject(JSON.toJSONString(map), SpsAdminEntity.class);
        return map;
    }


}
